package org.ojudge.ojudgecodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.util.List;

public class DockerDemo {
    public static void main(String[] args) throws InterruptedException {
        //获取默认的DockerClient
        String image = "nginx:latest";
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

/*
        //拉取镜像
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
        PullImageResultCallback callback = new PullImageResultCallback(){
            @Override
            public void onNext(PullResponseItem item) {
                System.out.println("下载镜像：" + item.getStatus());
                super.onNext(item);
            }
        };
        pullImageCmd.exec(callback).awaitCompletion();
        System.out.println("下载完成");
*/

/*        //创建容器
        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(image);
        CreateContainerResponse createContainerResponse = createContainerCmd
                .withCmd("echo","Hello Docker")
                .exec();
        System.out.println("容器创建成功：" + createContainerResponse.getId());*/

        //获取容器列表
        List<Container> containerList = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container : containerList) {
            System.out.println(container);
        }

        //启动容器
        dockerClient.startContainerCmd(containerList.get(0).getId()).exec();

        //查看日志
        LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                System.out.println("日志：" + new String(item.getPayload()));
                super.onNext(item);
            }
        };
        dockerClient.logContainerCmd(containerList.get(0).getId())
                .withStdErr(true)
                .withStdOut(true)
                .exec(logContainerResultCallback)
                .awaitCompletion();

        //删除容器
        dockerClient.removeContainerCmd(containerList.get(0).getId()).withForce(true).exec();

        //停止容器
        dockerClient.stopContainerCmd(containerList.get(0).getId()).exec();

        //删除镜像
        dockerClient.removeImageCmd(image).exec();
    }
}
